package com.idea.id_generate.controller;

import com.idea.id_generate.model.query.IdQuery;
import com.idea.id_generate.model.query.ResolveIdQuery;
import com.idea.id_generate.service.SnowFlakeService;
import com.idea.id_generate.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.idea.id_generate.rest.ResponseCode;
import com.idea.id_generate.rest.ResponseEntityUtil;
import com.idea.id_generate.rest.ResponseWrapper;

@Slf4j
@RestController
@RequestMapping("/IdGenerate")
public class IdController {
    @Autowired SnowFlakeService snowFlake;

    /**
     *获取ID
     * @return 返回生成的ID
     */
    @GetMapping("/getId")
    public ResponseEntity<ResponseWrapper<?>> generateId(){
        try{
        snowFlake.initData(2, 3);
        return ResponseEntityUtil.success(ResponseWrapper.success(snowFlake.nextId()).build());
        }catch (ApiException e){
            log.info("获取ID错误");
            log.error(e.getMessage(), e);
            throw e;
        }catch (Exception e){
            log.info("获取ID系统错误");
            log.error(e.getMessage(), e);
            throw new ApiException(ResponseCode.IdError.GET_ID_ERROR.getMessage(), ResponseCode.IdError.GET_ID_ERROR.getCode());
        }
    }

    /**
     * <h>根据传入参数生成ID</h>
     * @param idQuery 生成ID需要的参数
     * @return 生成的ID
     */
    @PostMapping("/generateId")
    public ResponseEntity<ResponseWrapper<?>> generateId(@RequestBody IdQuery idQuery){
        /**
         * <P>根据传入的信息生成ID</P>
         */
        try{
            snowFlake.initData(idQuery.getDataCenterId(), idQuery.getWorkerId());
            return ResponseEntityUtil.success(ResponseWrapper.success(snowFlake.nextId()).build());
        }catch (ApiException e){
            log.info("获取ID错误");
            log.error(e.getMessage(), e);
            throw e;
        }catch (Exception e){
            log.info("获取ID系统错误");
            log.error(e.getMessage(), e);
            throw new ApiException(ResponseCode.IdError.GET_ID_ERROR.getMessage(), ResponseCode.IdError.GET_ID_ERROR.getCode());
        }
    }

    @PostMapping("resolveId")
    public ResponseEntity<ResponseWrapper<?>> resolveId(@RequestBody ResolveIdQuery resolveIdQuery){
        try{
            return ResponseEntityUtil.success(ResponseWrapper.success(SnowFlakeService.resolveId(resolveIdQuery)).build());
        }catch (ApiException e){
            log.info("获取ID错误");
            log.error(e.getMessage(), e);
            throw e;
        }catch (Exception e){
            log.info("获取ID系统错误");
            log.error(e.getMessage(), e);
            throw new ApiException(ResponseCode.IdError.GET_ID_ERROR.getMessage(), ResponseCode.IdError.GET_ID_ERROR.getCode());
        }
    }
}
